"""
绘制轮廓内接圆，返回直径长度
"""
import os
import cv2
import numpy as np
import csv


def inner_circle(filedir, outputdir):
    # 读取图片，转灰度
    mask = cv2.imread(filedir)
    fname = filedir.split('/')[-1]
    mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
    # 二值化
    ret, mask_gray = cv2.threshold(mask_gray, 127, 255, cv2.THRESH_BINARY)

    # 识别轮廓
    contours, _ = cv2.findContours(mask_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    diameters = []  # 存储所有轮廓的直径

    for contour in contours:
        # 计算到轮廓的距离
        raw_dist = np.empty(mask_gray.shape, dtype=np.float32)
        for i in range(mask_gray.shape[0]):
            for j in range(mask_gray.shape[1]):
                raw_dist[i, j] = cv2.pointPolygonTest(contour, (j, i), True)

        # 获取最大值即内接圆半径，中心点坐标
        minVal, maxVal, _, maxDistPt = cv2.minMaxLoc(raw_dist)

        # 半径：maxVal  圆心：maxDistPt
        maxVal = abs(maxVal)
        radius = int(maxVal)

        # 绘制内切圆
        cv2.circle(mask, maxDistPt, radius, (0, 255, 0), 2, 1, 0)
        # 绘制圆心
        cv2.circle(mask, maxDistPt, 1, (0, 255, 0), 2, 1, 0)

        # 保存处理后的图片
        cv2.imwrite(outputdir + '/' + 'circle_' + fname, mask)
        if 0 < 2 * radius <= 40:
            diameters.append(2 * radius)
        # diameters.append(2 * radius)
    if len(diameters) == 0:
        width = 0
    else:
        width = sorted(diameters)[-1]

    return width

def inner_circles(filedir, outputdir):
    with open('result.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['filename', 'diameters'])

        for file in os.listdir(filedir):
            # 读取图片，转灰度
            mask = cv2.imread(filedir + '/' + file)
            mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
            # 二值化
            ret, mask_gray = cv2.threshold(mask_gray, 127, 255, cv2.THRESH_BINARY)

            # 识别轮廓
            contours, _ = cv2.findContours(mask_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            diameters = []  # 存储所有轮廓的直径

            for contour in contours:
                # 计算到轮廓的距离
                raw_dist = np.empty(mask_gray.shape, dtype=np.float32)
                for i in range(mask_gray.shape[0]):
                    for j in range(mask_gray.shape[1]):
                        raw_dist[i, j] = cv2.pointPolygonTest(contour, (j, i), True)

                # 获取最大值即内接圆半径，中心点坐标
                minVal, maxVal, _, maxDistPt = cv2.minMaxLoc(raw_dist)

                # 半径：maxVal  圆心：maxDistPt
                maxVal = abs(maxVal)
                radius = int(maxVal)

                # 绘制内切圆
                cv2.circle(mask, maxDistPt, radius, (0, 255, 0), 2, 1, 0)
                # 绘制圆心
                cv2.circle(mask, maxDistPt, 1, (0, 255, 0), 2, 1, 0)

                # 保存处理后的图片
                cv2.imwrite(outputdir + '/' + 'circle_' + file, mask)

                diameters.append(2 * radius)

            writer.writerow([file, diameters])


# inner_circles('luopu/cropped', 'luopu/circle')
# inner_circle('luopu/cropped/cropped_image_116536289.tif', 'luopu/circle')
